<?php

class matrixActions extends sfActions
{
  protected $table = false;

  public function  preExecute()
  {
    parent::preExecute();

    $this->table = Doctrine::getTable('Parameter');
  }

  /**
   * 
   * @param sfWebRequest $request
   */
  public function executeIndex(sfWebRequest $request)
  {
    $this->groups = $this->table->getPrimaryGroups();
  }

  /**
   * Create new table
   *
   * @param sfWebRequest $request
   * @return sfView
   */
  public function executeNew(sfWebRequest $request)
  {
    if($request->hasParameter('group_1') && $request->hasParameter('group_2'))
    {
      if($request->getParameter('group_1') != $request->getParameter('group_2'))
      {
        // We need these group in the template
        $this->group_top  = $request->getParameter('group_1');
        $this->group_left = $request->getParameter('group_2');

        $this->left = $this->table->getConnectedWith($this->group_top);
        $this->top  = $this->table->getConnectedWith($this->group_left);

        // We will continue only if we have at leat one parameter
        // in each category
        if(!$this->left || !$this->top)
        {
          throw new sfException('You must have at least one parameter in each category', 500);
        }
      } else throw new sfException('You must select different categories to continue', 500);
    } else throw new sfException('You have not selected categories to continue', 500);
  }

  /**
   * Save changes
   *
   * @param sfWebRequest $request 
   */
  public function executeSave(sfWebRequest $request)
  {
    foreach($request->getParameter('matrix') as $left => $top_array){
      foreach($top_array as $top => $value) {
        $matrix = new Matrix;

        $matrix->group_2 = $request->getParameter('left');
        $matrix->group_1 = $request->getParameter('top');
        $matrix->param_1 = $left;
        $matrix->param_2 = $top;
        $matrix->intersect = $value;

        $matrix->save();
      }
    }

    $this->redirect('/backend_dev.php/matrix');

    return sfView::NONE;
  }
}
